package ai.mspbots.poc.es.service;

import ai.mspbots.poc.es.entity.Document;
import cn.hutool.json.JSONUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.FuzzyQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService {

    @Autowired
    private RestHighLevelClient client;

    public List<Document> fuzzySearch(String index, String field, String searchTerm) {
        try {
            // 创建搜索请求
            SearchRequest searchRequest = new SearchRequest(index);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            // 创建模糊查询
            FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery(field, searchTerm)
                .fuzziness(Fuzziness.TWO) // 自动模糊匹配
                // .prefixLength(1) // 前缀长度
                    ;

            searchSourceBuilder.query(fuzzyQuery);
            searchRequest.source(searchSourceBuilder);

            // 执行搜索
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            List<Document> documents = new ArrayList<>();

            for (SearchHit hit : response.getHits().getHits()) {
                String source = hit.getSourceAsString();
                Document doc = JSONUtil.toBean(source, Document.class);
                // 继续提取其他字段
                documents.add(doc);
            }
            ArrayList<Object> objects = new ArrayList<>();


            return documents;
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }
}